<?php
namespace App\Config;

use App\Cache\Cache;
use App\Cache\Db;
use App\Cache\Redis;
use App\Di\Di;
use App\Handles\RouterHandle;

class Bootstrap
{
    /**
     * @var array
     */
    private $config = [];

    public function __construct ($envConfig)
    {
        $this->config = array_merge($envConfig, include APP_PATH . '/Config/Config.php');
    }

    public function start ()
    {
        require_once BASE_PATH . '/vendor/autoload.php';
        $this->registerServices();
        $this->registerAutoLoaders();
        $this->run(function ()
        {
            return new Request();
        });
        $this->response(function ()
        {
            return new Response();
        });
    }

    public function registerServices ()
    {
        $di = new Di();
        $di->set('redis', function ()
        {
            return new Redis([
                'host' => '127.0.0.1',
                'port' => 6379
            ]);
        });
        $di->setShared('cache', function () use ($di)
        {
            $cache = new Cache([
                'connect' => 'redis'
            ]);
            $cache->setDi($di);
            return $cache;
        });
        $di->setShared('db', function () use ($di)
        {
            $cache = new Db([
                'connect' => 'redis'
            ]);
            $cache->setDi($di);
            return $cache;
        });
    }

    public function registerAutoLoaders ()
    {
        $loader = new Loader();
        //加载路由机制
        $loader->load(function ()
        {
            return new RouterHandle();
        });
    }

    /**
     *
     *
     * @param \Closure $response
     *
     * @return mixed
     */
    public function response (\Closure $response)
    {
        $data = [
            'code' => 200,
            'msg'  => '成功'
        ];
        return $response()->response($data);
    }

    /**
     * 运行应用
     *
     * @param \Closure $request
     */
    public function run (\Closure $request)
    {
        $di = new Di();
        $di->set('request', $request);
        $loader  = new Loader();
        $handles = $loader->getHandles();
        foreach ($handles as $handle)
        {
            $handle()->register($di);
        }
    }

}